package com.hhxy.service.impl;

import com.hhxy.constants.SystemConstants;
import com.hhxy.model.dto.LoginUser;
import com.hhxy.model.dto.UserLoginDto;
import com.hhxy.model.vo.LoginUserInfoVo;
import com.hhxy.model.vo.UserInfoVo;
import com.hhxy.service.LoginService;
import com.hhxy.utils.BeanCopyUtils;
import com.hhxy.utils.JwtUtils;
import com.hhxy.utils.SecurityUtils;
import com.hhxy.utils.redis.RedisCache;
import com.hhxy.utils.response.ResponseResult;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author ghp
 * @date 2023/4/25
 * @title
 * @description
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisCache redisCache;


    /**
     * 用户登录
     *
     * @param userLoginDto
     * @return
     */
    @Override
    public ResponseResult login(UserLoginDto userLoginDto) {
        // 校验账号和密码是否正确
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userLoginDto.getUserName(), userLoginDto.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }

        // 用户名和密码正确，获取userId生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        Long userId = loginUser.getUser().getId();
        String token = JwtUtils.createJWT(userId.toString());

        // 将用户信息存入Redis中
        redisCache.setCacheObject(SystemConstants.LOGIN_USER + userId, loginUser);

        // 封装VO，响应数据
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser, UserInfoVo.class);
        LoginUserInfoVo loginUserInfoVo = new LoginUserInfoVo(token, userInfoVo);
        return ResponseResult.okResult(loginUserInfoVo);
    }

    /**
     * 用户退出
     */
    @Override
    public ResponseResult logout() {
        // 获取当前登录的用户id
        Long userId = SecurityUtils.getUserId();
        // 根据userId删除存储在Redis中的用户信息
        redisCache.deleteObject(SystemConstants.LOGIN_USER + userId);
        return ResponseResult.okResult();
    }
}
